<template>
  <div class="device-analysis-container">
    <el-card shadow="hover">
      <template #header>
        <div class="header-container">
          <h3>设备数据分析</h3>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="exportData">导出数据</el-button>
            <el-button type="success" size="small" @click="handleMoreActions('dashboard-mode')">数据大屏</el-button>
          </div>
        </div>
      </template>
      <div class="filter-row">
        <el-form :inline="!isMobile" :model="filterForm" class="responsive-form">
          <el-form-item label="用户">
            <el-select 
              v-model="filterForm.userId" 
              placeholder="请选择用户" 
              clearable 
              @change="handleUserChange"
              :style="isMobile ? 'width: 100%' : ''"
            >
              <el-option label="全部用户" value=""></el-option>
              <el-option 
                v-for="user in userOptions" 
                :key="user.id" 
                :label="user.username" 
                :value="user.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备">
            <el-select 
              v-model="filterForm.deviceId" 
              placeholder="请选择设备" 
              clearable
              :style="isMobile ? 'width: 100%' : ''"
            >
              <el-option label="用户所有设备" value=""></el-option>
              <el-option 
                v-for="device in deviceOptions" 
                :key="device.id" 
                :label="device.name || device.serialNumber"                :value="device.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              :style="isMobile ? 'width: 100%' : ''"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="analyzeData">分析</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>      <!-- 设备总览卡片 -->
      <div v-loading="loading">
        <el-row :gutter="20" class="metric-cards" v-if="hasData">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-card shadow="hover" class="metric-card">
              <div class="card-title">设备总数</div>
              <div class="card-value">{{ deviceMetrics.totalCount }}</div>
              <div class="card-subtitle">在线: {{ deviceMetrics.onlineCount }} ({{ deviceMetrics.onlineRate }})</div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-card shadow="hover" class="metric-card">
              <div class="card-title">电量状态</div>
              <div class="card-value">
                <el-tag type="success">正常: {{ deviceMetrics.batteryStatus.normal }}</el-tag>
                <el-tag type="warning" style="margin-left: 8px;">低电量: {{ deviceMetrics.batteryStatus.low }}</el-tag>
                <el-tag type="danger" style="margin-left: 8px;">极低: {{ deviceMetrics.batteryStatus.critical }}</el-tag>
              </div>
              <div class="card-subtitle">平均电量: {{ deviceMetrics.batteryStatus.average }}%</div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-card shadow="hover" class="metric-card">
              <div class="card-title">设备健康状态</div>
              <div class="card-value">
                <el-tag type="success">正常: {{ deviceMetrics.healthStatus.normal }}</el-tag>
                <el-tag type="warning" style="margin-left: 8px;">警告: {{ deviceMetrics.healthStatus.warning }}</el-tag>
                <el-tag type="danger" style="margin-left: 8px;">故障: {{ deviceMetrics.healthStatus.error }}</el-tag>
              </div>
              <div class="card-subtitle">平均传感器健康: {{ deviceMetrics.healthStatus.average }}%</div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-card shadow="hover" class="metric-card">
              <div class="card-title">数据收集</div>
              <div class="card-value">{{ deviceMetrics.dataPoints }}条</div>
              <div class="card-subtitle">数据完整率: {{ deviceMetrics.dataIntegrity }}%</div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 设备状态表格 -->
        <el-card shadow="hover" class="device-table-card" v-if="hasData">
          <template #header>
            <div class="chart-header">
              <h4>设备状态概览</h4>
              <div class="chart-actions">
                <el-input
                  placeholder="搜索设备名称或ID"
                  v-model="deviceSearchQuery"
                  prefix-icon="el-icon-search"
                  size="small"
                  clearable
                  style="width: 200px; margin-right: 10px;"
                  @input="handleDeviceSearch"
                />
                <el-select 
                  v-model="currentDeviceGroup" 
                  placeholder="设备分组"
                  size="small"
                  style="width: 150px; margin-right: 10px;"
                  @change="handleDeviceGroupChange">
                  <el-option-group label="系统分组">
                    <el-option
                      v-for="group in deviceGroups"
                      :key="group.id"
                      :label="group.name"
                      :value="group.id">
                    </el-option>
                  </el-option-group>
                  <el-option-group label="自定义分组" v-if="customGroups.length > 0">
                    <el-option
                      v-for="group in customGroups"
                      :key="group.id"
                      :label="group.name"
                      :value="group.id">
                    </el-option>
                  </el-option-group>
                </el-select>
                <el-select 
                  v-model="selectedDevices" 
                  placeholder="选择对比设备"
                  multiple
                  collapse-tags
                  style="width: 240px; margin-right: 10px;"
                  @change="updateDeviceComparison">
                  <el-option 
                    v-for="device in deviceList" 
                    :key="device.id" 
                    :label="device.deviceName" 
                    :value="device.id">
                  </el-option>
                </el-select>
                <el-dropdown @command="handleMoreActions" split-button type="primary" size="small">
                  更多操作
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="save-group">保存当前选择为分组</el-dropdown-item>
                      <el-dropdown-item command="manage-groups">管理自定义分组</el-dropdown-item>
                      <el-dropdown-item command="export-selected" :disabled="!selectedDevices.length">导出选中设备数据</el-dropdown-item>
                      <el-dropdown-item command="compare-selected" :disabled="selectedDevices.length < 2">对比选中设备</el-dropdown-item>
                      <el-dropdown-item command="dashboard-mode">数据大屏模式</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>
          <el-table
            :data="deviceTableData"
            border
            style="width: 100%"
            height="350"
            @selection-change="handleDeviceSelection"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="deviceName" label="设备名称" sortable></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="batteryLevel" label="电量" width="150">
              <template #default="scope">
                <el-progress 
                  :percentage="scope.row.batteryLevel" 
                  :status="getBatteryStatus(scope.row.batteryLevel)"
                  :stroke-width="6"
                  :text-inside="true"
                ></el-progress>
              </template>
            </el-table-column>
            <el-table-column prop="usageTime" label="使用时长" sortable width="100"></el-table-column>
            <el-table-column prop="lastMaintenance" label="最后维护" sortable width="110"></el-table-column>
            <el-table-column prop="lastActive" label="最后活动" sortable width="160"></el-table-column>
          </el-table>
          <div style="text-align: center; margin-top: 15px;">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalDeviceCount"
              :page-size="devicePageSize"
              @current-change="handleDevicePageChange"
              :current-page="deviceCurrentPage"
            ></el-pagination>          </div>
        </el-card>
        
        <!-- 设备数据为空时显示 -->
        <div v-if="(!hasData || (deviceTableData.length === 0 && !loading))" class="empty-data">
          <el-empty description="暂无设备数据，请尝试刷新页面或选择其他用户">
            <el-button type="primary" @click="refreshDevicesList">加载数据</el-button>
          </el-empty>
        </div>
        
        <!-- 设备使用情况卡片 -->
        <el-card v-if="hasData" shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <h4>设备使用情况对比</h4>
              <div class="chart-actions">
                <el-radio-group v-model="timeGranularity" size="small" @change="updateUsageChart">
                  <el-radio-button label="hour">小时</el-radio-button>
                  <el-radio-button label="day">天</el-radio-button>
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                </el-radio-group>
                <el-select 
                  v-model="usageChartMetric"
                  placeholder="指标"
                  size="small"
                  style="margin-left: 10px; width: 120px;"
                  @change="updateUsageChart">
                  <el-option label="使用时长" value="duration"></el-option>
                  <el-option label="使用次数" value="activeTimes"></el-option>
                  <el-option label="电量消耗" value="batteryUsage"></el-option>
                </el-select>
              </div>
            </div>          </template>
          <div id="usageChart" ref="usageChart" style="height: 350px;"></div>
        </el-card>        <!-- 设备异常检测 -->
        <el-card v-if="hasData" shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <h4>设备异常检测与对比</h4>
              <div class="chart-actions">
                <el-tooltip content="标记异常值" placement="top">
                  <el-switch
                    v-model="showAnomalies"
                    active-text="异常点"
                    @change="updateAnomalyChart"
                  />
                </el-tooltip>
                <el-select 
                  v-model="anomalyMetric" 
                  placeholder="异常指标" 
                  style="margin-left: 10px; width: 140px;"
                  size="small"
                  @change="updateAnomalyChart">
                  <el-option label="PM2.5浓度" value="pm25"></el-option>
                  <el-option label="PM10浓度" value="pm10"></el-option>
                  <el-option label="CO2浓度" value="co2"></el-option>
                  <el-option label="TVOC浓度" value="tvoc"></el-option>
                  <el-option label="温度" value="temperature"></el-option>
                </el-select>
              </div>
            </div>          </template>
          <div id="anomalyChart" ref="anomalyChart" style="height: 350px;"></div>
        </el-card>        <!-- 设备问题告警分布 -->
        <el-card v-if="hasData" shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <h4>设备告警分布对比</h4>
              <div class="chart-actions">
                <el-radio-group v-model="alertViewType" size="small" @change="updateAlertChart">
                  <el-radio-button label="pie">饼图</el-radio-button>
                  <el-radio-button label="bar">柱状图</el-radio-button>
                </el-radio-group>
                <el-select 
                  v-model="alertGroupBy" 
                  placeholder="分组方式" 
                  style="margin-left: 10px; width: 120px;"
                  size="small"
                  @change="updateAlertChart">
                  <el-option label="告警类型" value="type"></el-option>
                  <el-option label="设备" value="device"></el-option>
                  <el-option label="严重程度" value="severity"></el-option>
                </el-select>              </div>
            </div>
          </template>
          <div id="alertChart" ref="alertChart" style="height: 350px;"></div>
        </el-card>        <!-- 维护记录 -->
        <el-card v-if="hasData" shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <h4>设备维护记录</h4>
              <div class="chart-actions">
                <el-select 
                  v-model="maintenanceDevice"
                  placeholder="选择设备"
                  clearable
                  style="width: 180px;"
                  @change="updateMaintenanceRecords">
                  <el-option 
                    v-for="device in deviceList" 
                    :key="device.id" 
                    :label="device.name" 
                    :value="device.id">
                  </el-option>
                </el-select>
              </div>
            </div>
          </template>
          <el-tabs v-model="maintenanceTab" @tab-click="handleMaintenanceTabChange">
            <el-tab-pane label="时间线" name="timeline">
              <el-timeline>
                <el-timeline-item
                  v-for="(activity, index) in maintenanceRecords"
                  :key="index"
                  :timestamp="activity.time"
                  :type="activity.type"
                  :color="activity.color"
                  :size="activity.size"
                >
                  <span v-if="activity.deviceName">[{{ activity.deviceName }}] </span>{{ activity.content }}
                </el-timeline-item>
              </el-timeline>
            </el-tab-pane>
            <el-tab-pane label="统计" name="stats">
              <div ref="maintenanceStatsChart" style="height: 300px;"></div>
            </el-tab-pane>
          </el-tabs>
        </el-card>        <!-- 历史数据记录 -->
        <el-card v-if="hasData" shadow="hover" class="data-table-card">
          <template #header>
            <div class="chart-header">
              <h4>历史数据记录</h4>
              <div class="chart-actions">
                <el-button size="small" @click="exportTableData">导出表格</el-button>
                <el-select 
                  v-model="dataRecordDevice"
                  placeholder="选择设备"
                  clearable
                  style="width: 180px; margin-left: 10px;"
                  @change="fetchHistoricalData">
                  <el-option 
                    v-for="device in deviceList" 
                    :key="device.id" 
                    :label="device.name" 
                    :value="device.id">
                  </el-option>
                </el-select>
              </div>
            </div>
          </template>
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            height="400"
            v-loading="tableLoading"
          >
            <el-table-column prop="deviceName" label="设备" sortable width="120" v-if="!dataRecordDevice" />
            <el-table-column prop="timestamp" label="时间" sortable width="150" />
            <el-table-column prop="pm25" label="PM2.5" sortable />
            <el-table-column prop="pm10" label="PM10" sortable />
            <el-table-column prop="temperature" label="温度(℃)" sortable />
            <el-table-column prop="humidity" label="湿度(%)" sortable />
            <el-table-column prop="tvoc" label="TVOC" sortable />
            <el-table-column prop="co2" label="CO2(ppm)" sortable />
            <el-table-column prop="hcho" label="甲醛" sortable />
            <el-table-column prop="batteryLevel" label="电量(%)" sortable />
            <el-table-column prop="workMode" label="工作模式" />
          </el-table>
          <div class="pagination-container">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              :page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </el-card>
      <!-- 移除调试组件 -->
    <!-- 设备分组管理对话框 -->
    <el-dialog
      title="设备分组管理"
      v-model="showGroupDialog"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-tabs v-model="groupDialogTab">
        <el-tab-pane label="创建新分组" name="create">
          <el-form :model="newGroupForm" label-width="100px" ref="groupFormRef" :rules="groupFormRules">
            <el-form-item label="分组名称" prop="name">
              <el-input v-model="newGroupForm.name" placeholder="请输入分组名称"></el-input>
            </el-form-item>
            <el-form-item label="选择设备">
              <el-select 
                v-model="newGroupForm.deviceIds"
                multiple
                collapse-tags
                placeholder="请选择设备"
                style="width: 100%;">
                <el-option
                  v-for="device in deviceList"
                  :key="device.id"
                  :label="device.deviceName"
                  :value="device.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveDeviceGroup">保存分组</el-button>
              <el-button @click="resetGroupForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="管理分组" name="manage">
          <div v-if="customGroups.length === 0" class="empty-custom-groups">
            <el-empty description="暂无自定义分组" :image-size="100">
              <el-button type="primary" @click="groupDialogTab = 'create'">创建分组</el-button>
            </el-empty>
          </div>
          <el-table v-else :data="customGroups" style="width: 100%">
            <el-table-column prop="name" label="分组名称"></el-table-column>
            <el-table-column label="设备数量" align="center">
              <template #default="scope">
                <el-tag type="info">{{ scope.row.deviceIds.length }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="mini" @click="editGroup(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="deleteGroup(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    
    <!-- 数据大屏模式对话框 -->
    <el-dialog
      title="数据大屏"
      v-model="showDashboardDialog"
      fullscreen
      :destroy-on-close="true"
      :close-on-click-modal="false"
      append-to-body
      custom-class="dashboard-dialog"
    >
      <div class="dashboard-container">
        <div class="dashboard-header">
          <h2>空气质量监测数据大屏</h2>
          <div class="dashboard-time">{{ currentTime }}</div>
          <div class="dashboard-controls">
            <el-select 
              v-model="dashboardDeviceGroup" 
              placeholder="选择设备分组"
              size="small"
              style="width: 150px;">
              <el-option
                v-for="group in [...deviceGroups, ...customGroups]"
                :key="group.id"
                :label="group.name"
                :value="group.id">
              </el-option>
            </el-select>
            <el-button type="primary" icon="el-icon-refresh" circle size="small" @click="refreshDashboard"></el-button>
            <el-button type="danger" @click="showDashboardDialog = false" icon="el-icon-close" circle size="small"></el-button>
          </div>
        </div>
        <div class="dashboard-content">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="dashboard-card">
                <div class="dashboard-title">设备总览</div>
                <div class="dashboard-info">
                  <div class="info-item">
                    <span class="info-label">设备总数</span>
                    <span class="info-value">{{ deviceMetrics.totalCount }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">在线率</span>
                    <span class="info-value">{{ deviceMetrics.onlineRate }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">数据完整率</span>
                    <span class="info-value">{{ deviceMetrics.dataIntegrity }}%</span>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="dashboard-card">
                <div class="dashboard-title">平均电量</div>
                <div class="dashboard-battery">
                  <el-progress type="dashboard" :percentage="deviceMetrics.batteryStatus.average" :color="getBatteryColor"></el-progress>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="dashboard-card">
                <div class="dashboard-title">设备健康状态</div>
                <div ref="dashboardHealthChart" style="height: 200px;"></div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
              <div class="dashboard-card">
                <div class="dashboard-title">设备异常检测分布</div>
                <div ref="dashboardAnomalyChart" style="height: 300px;"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="dashboard-card">
                <div class="dashboard-title">告警分布统计</div>
                <div ref="dashboardAlertChart" style="height: 300px;"></div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="24">
              <div class="dashboard-card">
                <div class="dashboard-title">
                  <span>关键设备状态</span>
                  <el-radio-group v-model="dashboardSortBy" size="small" style="float: right;">
                    <el-radio-button label="status">按状态</el-radio-button>
                    <el-radio-button label="battery">按电量</el-radio-button>
                    <el-radio-button label="active">按活跃度</el-radio-button>
                  </el-radio-group>
                </div>
                <div class="dashboard-device-list">
                  <el-table :data="dashboardDeviceList" size="small" :show-header="false" style="width: 100%;">
                    <el-table-column width="60">
                      <template #default="scope">
                        <el-avatar :size="40" :style="{ backgroundColor: getDeviceAvatarColor(scope.row) }">
                          {{ scope.row.deviceName.substring(0, 2) }}
                        </el-avatar>
                      </template>
                    </el-table-column>
                    <el-table-column prop="deviceName">
                      <template #default="scope">
                        <div class="device-info">
                          <div class="device-name">{{ scope.row.deviceName }}</div>
                          <div class="device-status">
                            <el-tag :type="getStatusType(scope.row.status)" size="small">{{ scope.row.status }}</el-tag>
                            <span style="margin-left: 10px;">{{ scope.row.lastActive }}</span>
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column width="180">
                      <template #default="scope">
                        <el-progress :percentage="scope.row.batteryLevel" :status="getBatteryStatus(scope.row.batteryLevel)" :stroke-width="6"></el-progress>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, nextTick, onMounted } from 'vue';
import * as echarts from 'echarts/core';
import { LineChart, BarChart, ScatterChart, PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  ToolboxComponent,
  LegendComponent,
  MarkPointComponent,
  MarkLineComponent
} from 'echarts/components';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { 
  getDeviceStatusData, 
  getDeviceUsageStats, 
  getDeviceAnomalies, 
  getDeviceAlertDistribution, 
  getDeviceMaintenanceRecords,
  getUserDevices,
  getUsersList,
  exportDeviceData
} from '../../api/deviceAnalysis';
import { ElMessage, ElMessageBox } from 'element-plus';
import { generateDeviceName } from '../../config/deviceConfig';

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LineChart,
  BarChart,
  ScatterChart,
  PieChart,
  CanvasRenderer,
  UniversalTransition,
  DataZoomComponent,
  ToolboxComponent,
  LegendComponent,
  MarkPointComponent,
  MarkLineComponent
]);

export default {
  name: 'DeviceDataAnalysis',
  setup() {
    // 响应式状态
    const loading = ref(false);
    const tableLoading = ref(false);
    const hasData = ref(false);
    const isMobile = ref(window.innerWidth <= 768);
    
    // 多设备支持相关变量
    const deviceList = ref([]);
    const selectedDevices = ref([]);
    const deviceTableData = ref([]);
    const totalDeviceCount = ref(0);
    const deviceCurrentPage = ref(1);
    const devicePageSize = ref(10);
    const dataRecordDevice = ref('');
    const maintenanceDevice = ref('');
    const maintenanceTab = ref('timeline');
    const usageChartMetric = ref('duration');
    const anomalyMetric = ref('pm25');    const alertViewType = ref('pie');
    const alertGroupBy = ref('type');
    
    // 分组管理相关变量
    const showGroupDialog = ref(false);
    const groupDialogTab = ref('create');
    const isEditingGroup = ref(false);
    const currentEditingGroupId = ref('');
    const deviceSearchQuery = ref('');
    const groupFormRules = {
      name: [
        { required: true, message: '请输入分组名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ]
    };
    
    // 数据大屏相关变量
    const showDashboardDialog = ref(false);
    const currentTime = ref('');
    const dashboardTimer = ref(null);
    const dashboardDeviceGroup = ref('all');
    const dashboardSortBy = ref('status');
    const dashboardDeviceList = ref([]);
    
    // 设备分组功能
    const deviceGroups = ref([
      { id: 'all', name: '全部设备', deviceIds: [] },
      { id: 'online', name: '在线设备', deviceIds: [] },
      { id: 'offline', name: '离线设备', deviceIds: [] },
      { id: 'warning', name: '警告设备', deviceIds: [] },
      { id: 'lowBattery', name: '低电量设备', deviceIds: [] }
    ]);
    const currentDeviceGroup = ref('all');
    const customGroups = ref([]);
    const isAddingGroup = ref(false);
    const newGroupForm = reactive({
      name: '',
      deviceIds: []
    });
    
    // 设备整体统计指标
    const deviceMetrics = ref({
      totalCount: 0,
      onlineCount: 0,
      onlineRate: '0%',
      batteryStatus: {
        normal: 0,
        low: 0,
        critical: 0,
        average: 0
      },
      healthStatus: {
        normal: 0,
        warning: 0,
        error: 0,
        average: 0
      },
      dataPoints: 0,
      dataIntegrity: 0
    });
    // ESLint 无法识别在模板中使用的响应式变量，添加注释避免未使用变量警告
    const isDev = ref(process.env.NODE_ENV === 'development'); // eslint-disable-line no-unused-vars
    const filterForm = reactive({
      userId: '',
      deviceId: '',
      dateRange: [new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000), new Date()],
    });
    // 只保留实际用到的变量和方法，后续如有未用变量报错请继续精简
    const userOptions = ref([]);
    const deviceOptions = ref([]);
    const dateShortcuts = [
      {
        text: '最近一周',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 7 * 24 * 60 * 60 * 1000);
          return [start, end];
        }
      },
      {
        text: '最近一个月',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setMonth(start.getMonth() - 1);
          return [start, end];
        }
      },
      {
        text: '最近三个月',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setMonth(start.getMonth() - 3);
          return [start, end];
        }
      }
    ];
    const timeGranularity = ref('day');
    const showAnomalies = ref(true);
    const tableData = ref([]);
    const total = ref(100);
    const pageSize = ref(10);
    const currentPage = ref(1);    const usageChart = ref(null);
    const anomalyChart = ref(null);
    const alertChart = ref(null);
    const deviceAlertData = ref([
      { name: '设备离线', value: 0 },
      { name: '低电量', value: 0 },
      { name: '传感器故障', value: 0 },
      { name: '硬件故障', value: 0 },
      { name: '其他', value: 0 }
    ]);
    
    // 设备状态信息
    const deviceStatus = ref({type: 'info', text: '未知'});
    const deviceLastActive = ref('未知');
    const deviceBattery = ref(0);
    const deviceBatteryStatus = ref('');
    const batteryLifeRemaining = ref('未知');
    const sensorHealth = ref(0);
    const sensorHealthStatus = ref('');
    const sensorHealthMessage = ref('');
    const deviceUsageTime = ref('0小时');
    const usageFrequency = ref('未知');
    const maintenanceRecords = ref([]);
    
    // 更新设备指标卡片数据
    const updateDeviceMetrics = (statusData) => {
      // 设备状态
      if (statusData.status === 'online') {
        deviceStatus.value = {type: 'success', text: '在线'};
      } else if (statusData.status === 'offline') {
        deviceStatus.value = {type: 'danger', text: '离线'};
      } else if (statusData.status === 'warning') {
        deviceStatus.value = {type: 'warning', text: '警告'};
      } else {
        deviceStatus.value = {type: 'info', text: '未知'};
      }
      
      // 最后活跃时间
      if (statusData.lastActive) {
        const lastActiveDate = new Date(statusData.lastActive);
        deviceLastActive.value = lastActiveDate.toLocaleString('zh-CN');
      } else {
        deviceLastActive.value = '未知';
      }
      
      // 电池状态
      deviceBattery.value = statusData.battery || 0;
      if (deviceBattery.value > 70) {
        deviceBatteryStatus.value = 'success';
      } else if (deviceBattery.value > 30) {
        deviceBatteryStatus.value = 'warning';
      } else {
        deviceBatteryStatus.value = 'exception';
      }
      
      // 预计续航
      batteryLifeRemaining.value = statusData.batteryLife || '未知';
      
      // 传感器健康
      sensorHealth.value = statusData.sensorHealth || 0;
      if (sensorHealth.value > 80) {
        sensorHealthStatus.value = 'success';
        sensorHealthMessage.value = '传感器工作正常';
      } else if (sensorHealth.value > 50) {
        sensorHealthStatus.value = 'warning';
        sensorHealthMessage.value = '传感器需要校准';
      } else {
        sensorHealthStatus.value = 'exception';
        sensorHealthMessage.value = '传感器需要维修';
      }
      
      // 使用时长
      deviceUsageTime.value = statusData.usageTime || '0小时';
      
      // 使用频率
      usageFrequency.value = statusData.usageFrequency || '未知';
    };    const handleUserChange = async () => {
      if (filterForm.userId) {
        try {          // 创建默认模拟设备数据
          const defaultDevices = [
            { id: `device-${filterForm.userId}-1`, name: generateDeviceName(123, parseInt(filterForm.userId) || 1), serialNumber: `SN00${filterForm.userId}` },
            { id: `device-${filterForm.userId}-2`, name: generateDeviceName(456, parseInt(filterForm.userId) || 1), serialNumber: `SN01${filterForm.userId}` },
            { id: `device-${filterForm.userId}-3`, name: generateDeviceName(789, parseInt(filterForm.userId) || 1), serialNumber: `SN02${filterForm.userId}` }
          ];
          
          let response;
          try {
            // 尝试从API获取设备
            console.log('尝试从API获取用户设备...');
            response = await getUserDevices(filterForm.userId);
            
            // 检查API返回的数据是否有效
            if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
              console.log('使用API返回的设备列表');
              deviceOptions.value = response.data;
            } else {
              console.warn('API返回的设备列表为空或无效，使用默认模拟设备');
              deviceOptions.value = defaultDevices;
            }
          } catch (error) {
            console.error('获取用户设备失败，使用替代设备:', error);
            deviceOptions.value = defaultDevices;
          }
          
          console.log('最终设置的设备列表:', deviceOptions.value);
          
          // 确保deviceOptions不为空，这对自动选择设备很重要
          if (deviceOptions.value.length === 0) {
            console.warn('设备列表为空，添加默认模拟设备');
            deviceOptions.value = defaultDevices;
          }
          
          // 返回设备列表，方便后续处理
          return deviceOptions.value;
        } catch (error) {
          console.error('处理用户设备数据失败:', error);
          ElMessage.error('获取用户设备失败，请刷新页面重试');
          deviceOptions.value = [];
          return [];
        }
      } else {
        console.log('没有选择用户，清除设备列表');
        deviceOptions.value = [];
        filterForm.deviceId = '';
        return [];
      }
    };    // 处理设备表格选择变更
    const handleDeviceSelection = (selection) => {
      selectedDevices.value = selection.map(device => device.id);
      updateDeviceComparison();
    };
    
    // 处理设备表格分页变化
    const handleDevicePageChange = (newPage) => {
      deviceCurrentPage.value = newPage;
      updateDevicesList();
    };
      // 更新设备列表数据
    const updateDevicesList = () => {
      console.log('更新设备列表数据...');
      if (!deviceList.value || deviceList.value.length === 0) {
        console.log('设备列表为空，尝试重新获取设备');
        fetchDevicesList();
        return;
      }
      
      console.log('设备列表数据总数:', deviceList.value.length);
      const startIndex = (deviceCurrentPage.value - 1) * devicePageSize.value;
      const endIndex = startIndex + devicePageSize.value;
      deviceTableData.value = deviceList.value.slice(startIndex, endIndex);
      console.log('当前页设备数据:', deviceTableData.value.length);
    };    // 刷新设备列表数据 - 作为公开方法的封装
    const refreshDevicesList = () => {
      console.log('刷新设备列表数据...');
      fetchDevicesList();
    };
    
    // 获取设备列表数据
    const fetchDevicesList = async () => {
      console.log('开始获取设备列表数据...');
      // 如果已经有设备选项，使用这些数据
      if (deviceOptions.value && deviceOptions.value.length > 0) {
        console.log('使用现有的设备选项生成设备列表数据');          // 转换为设备表格所需的格式，并添加更多替代数据
        const devices = deviceOptions.value.map((device, index) => {
          return {
            id: device.id,
            deviceName: device.name || `设备${index + 1}`,
            status: ['正常', '电量低', '告警', '正常', '正常'][Math.floor(Math.random() * 5)],
            batteryLevel: Math.floor(Math.random() * 100),
            usageTime: `${Math.floor(Math.random() * 50) + 10}小时`,
            lastMaintenance: new Date(new Date().getTime() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
            lastActive: new Date(new Date().getTime() - Math.floor(Math.random() * 24 * 10) * 60 * 60 * 1000).toLocaleString('zh-CN')
          };
        });          // 创建额外的替代设备数据
        for (let i = deviceOptions.value.length; i < 20; i++) {
          devices.push({
            id: `device-${i + 1}`,
            deviceName: generateDeviceName(100 + i, i + 1),
            status: ['正常', '电量低', '告警', '正常', '正常'][Math.floor(Math.random() * 5)],
            batteryLevel: Math.floor(Math.random() * 100),
            usageTime: `${Math.floor(Math.random() * 50) + 10}小时`,
            lastMaintenance: new Date(new Date().getTime() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
            lastActive: new Date(new Date().getTime() - Math.floor(Math.random() * 24 * 10) * 60 * 60 * 1000).toLocaleString('zh-CN')
          });
        }
        
        deviceList.value = devices;
        totalDeviceCount.value = devices.length;
        updateDevicesList();
        updateDeviceMetricsData();      } else {        // 没有设备选项，创建默认设备数据
        const devices = [];
        for (let i = 0; i < 20; i++) {
          devices.push({
            id: `device-${i + 1}`,
            deviceName: generateDeviceName(100 + i, i + 1),
            status: ['正常', '电量低', '告警', '正常', '正常'][Math.floor(Math.random() * 5)],
            batteryLevel: Math.floor(Math.random() * 100),
            usageTime: `${Math.floor(Math.random() * 50) + 10}小时`,
            lastMaintenance: new Date(new Date().getTime() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
            lastActive: new Date(new Date().getTime() - Math.floor(Math.random() * 24 * 10) * 60 * 60 * 1000).toLocaleString('zh-CN')
          });
        }
        
        deviceList.value = devices;
        totalDeviceCount.value = devices.length;
        updateDevicesList();
        updateDeviceMetricsData();
      }
    };
      // 更新设备指标数据
    const updateDeviceMetricsData = () => {
      console.log('更新设备指标数据...');      if (!deviceList.value || deviceList.value.length === 0) {
        console.warn('设备列表为空，无法更新设备指标');
        // 设置一些默认值以防显示问题
        deviceMetrics.value = {
          totalCount: 0,
          onlineCount: 0,
          onlineRate: '0%',
          batteryStatus: {normal: 0, low: 0, critical: 0, average: 0},
          healthStatus: {normal: 0, warning: 0, error: 0, average: 0},
          dataPoints: 0,
          dataIntegrity: 0
        };
        return;
      }
      
      // 计算总数和在线数
      const totalCount = deviceList.value.length;
      const onlineCount = deviceList.value.filter(d => d.status === '正常').length;
      const onlineRate = `${Math.round((onlineCount / totalCount) * 100)}%`;
      
      // 计算电池状态分布
      let batteryNormal = 0;
      let batteryLow = 0;
      let batteryCritical = 0;
      let batterySum = 0;
      
      deviceList.value.forEach(device => {
        const battery = device.batteryLevel;
        batterySum += battery;
        
        if (battery >= 50) batteryNormal++;
        else if (battery >= 20) batteryLow++;
        else batteryCritical++;
      });
      
      // 计算设备健康状态分布
      const healthNormal = deviceList.value.filter(d => d.status === '正常').length;
      const healthWarning = deviceList.value.filter(d => d.status === '电量低').length;
      const healthError = deviceList.value.filter(d => d.status === '告警').length;
      
      // 更新设备指标
      deviceMetrics.value = {
        totalCount,
        onlineCount,
        onlineRate,
        batteryStatus: {
          normal: batteryNormal,
          low: batteryLow,
          critical: batteryCritical,
          average: Math.round(batterySum / totalCount)
        },
        healthStatus: {
          normal: healthNormal,
          warning: healthWarning,
          error: healthError,
          average: Math.round((healthNormal / totalCount) * 100)
        },
        dataPoints: Math.floor(Math.random() * 10000) + 5000,
        dataIntegrity: Math.floor(Math.random() * 10) + 90
      };
    };
    
    // 更新设备比较图表
    const updateDeviceComparison = () => {
      // 如果没有选择设备，使用默认选择前5个设备
      if (selectedDevices.value.length === 0 && deviceList.value && deviceList.value.length > 0) {
        selectedDevices.value = deviceList.value.slice(0, 5).map(d => d.id);
      }
      
      // 更新设备使用情况图表和异常检测图表
      updateUsageChart();
      updateAnomalyChart();
      updateAlertChart();
    };
    
    // 根据选定的设备获取历史数据
    const fetchHistoricalData = () => {
      // 更新查询条件，包括选择的设备
      loadHistoryTable();
    };
    
    // 更新维护记录显示
    const updateMaintenanceRecords = () => {
      // 根据选择的设备过滤维护记录
      // 如果没有选择特定设备，显示所有设备的记录
      if (!maintenanceDevice.value) {
        loadAllMaintenanceRecords();
      } else {
        loadDeviceMaintenanceRecords(maintenanceDevice.value);
      }
    };
    
    // 处理维护选项卡变化
    const handleMaintenanceTabChange = (tab) => {
      if (tab.paneName === 'stats') {
        updateMaintenanceStatsChart();
      }
    };
    
    // 更新维护统计图表
    const updateMaintenanceStatsChart = () => {
      if (!document.querySelector('#maintenanceStatsChart')) return;
      
      // 初始化维护统计图表
      const chartDom = document.querySelector('#maintenanceStatsChart');
      const maintenanceChart = echarts.init(chartDom);
      
      // 创建模拟的维护统计数据
      const maintenanceTypes = ['例行检查', '传感器校准', '电池更换', '固件更新', '硬件维修'];
      const maintenanceData = maintenanceTypes.map(type => {
        return {
          name: type,
          value: Math.floor(Math.random() * 10) + 1
        };
      });
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 10,
          data: maintenanceTypes
        },
        series: [
          {
            name: '维护类型',
            type: 'pie',
            radius: ['30%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: maintenanceData
          }
        ]
      };
      
      maintenanceChart.setOption(option);
    };
    
    // 获取状态类型
    const getStatusType = (status) => {
      if (status === '正常') return 'success';
      if (status === '警告' || status === '电量低') return 'warning';
      if (status === '错误' || status === '告警') return 'danger';
      return 'info';
    };
    
    // 获取电池状态
    const getBatteryStatus = (percentage) => {
      if (percentage < 20) return 'exception';
      if (percentage < 50) return 'warning';
      return 'success';    };
    
    // 加载所有设备的维护记录
    const loadAllMaintenanceRecords = () => {
      // 创建模拟的多设备维护记录
      const records = [];
      deviceList.value.forEach((device) => {        // 为每个设备随机生成1-3条维护记录
        const recordCount = Math.floor(Math.random() * 3) + 1;
        
        for (let i = 0; i < recordCount; i++) {
          const maintenanceTypes = [
            {content: '例行维护检查 - 所有参数正常', type: 'primary', color: '#409EFF'},
            {content: '传感器校准完成 - 提高PM2.5测量准确度', type: 'success', color: '#67C23A'},
            {content: '电池更换 - 更换新型号锂电池', type: 'warning', color: '#E6A23C'},
            {content: '固件更新 - v2.5.3版本，增加数据处理效率', type: 'info', color: '#909399'},
            {content: '硬件维修更换 - 主板故障排除', type: 'danger', color: '#F56C6C'},
            {content: '设备清洁 - 清理传感器表面灰尘', type: 'success', color: '#67C23A'},
            {content: 'WiFi模块升级 - 提高连接稳定性', type: 'primary', color: '#409EFF'},
            {content: '外壳更换 - 因老化出现裂缝', type: 'warning', color: '#E6A23C'},
            {content: '传感器模块更新 - 提高测量精度', type: 'info', color: '#909399'},
            {content: '设备搬迁 - 优化监测位置', type: 'primary', color: '#409EFF'},
            {content: '系统重置 - 排除连接问题', type: 'danger', color: '#F56C6C'}
          ];
          
          const randomType = maintenanceTypes[Math.floor(Math.random() * maintenanceTypes.length)];
          const daysAgo = Math.floor(Math.random() * 60) + 1;
          const date = new Date();
          date.setDate(date.getDate() - daysAgo);
          
          records.push({
            deviceName: device.deviceName,
            time: date.toLocaleString('zh-CN'),
            type: randomType.type,
            color: randomType.color,
            size: (i === 0) ? 'large' : 'normal',
            content: randomType.content
          });
        }
      });
      
      // 按时间排序
      records.sort((a, b) => new Date(b.time) - new Date(a.time));
      maintenanceRecords.value = records;
    };
    
    // 加载特定设备的维护记录
    const loadDeviceMaintenanceRecords = (deviceId) => {
      // 查找设备名
      const device = deviceList.value.find(d => d.id === deviceId);
      if (!device) return;
      
      // 创建模拟的维护记录
      const records = [];
      const maintenanceTypes = [
        {content: '例行维护检查', type: 'primary', color: '#409EFF'},
        {content: '传感器校准完成', type: 'success', color: '#67C23A'},
        {content: '电池更换', type: 'warning', color: '#E6A23C'},
        {content: '固件更新', type: 'info', color: '#909399'},
        {content: '硬件维修更换', type: 'danger', color: '#F56C6C'}
      ];
      
      // 生成5条维护记录
      for (let i = 0; i < 5; i++) {
        const randomType = maintenanceTypes[Math.floor(Math.random() * maintenanceTypes.length)];
        const daysAgo = Math.floor(Math.random() * 60) + 1;
        const date = new Date();
        date.setDate(date.getDate() - daysAgo);
        
        records.push({
          time: date.toLocaleString('zh-CN'),
          type: randomType.type,
          color: randomType.color,
          size: (i === 0) ? 'large' : 'normal',
          content: randomType.content
        });
      }
      
      // 按时间排序
      records.sort((a, b) => new Date(b.time) - new Date(a.time));
      maintenanceRecords.value = records;
    };
      const analyzeData = async () => {      // 如果没有选择用户，自动选择第一个用户
      if (!filterForm.userId && userOptions.value.length > 0) {
        filterForm.userId = userOptions.value[0].id;
        console.log(`已自动选择用户: ${userOptions.value[0].username || filterForm.userId}`);
        const devices = await handleUserChange();
        
        // 如果有设备，自动选择第一个设备
        if (devices && devices.length > 0) {
          filterForm.deviceId = devices[0].id;
          console.log(`已自动选择设备: ${devices[0].name || filterForm.deviceId}`);
        }
      } else if (!filterForm.userId) {
        console.warn('没有用户可选，加载默认用户数据');
        // 没有用户可选，尝试重新加载默认用户数据
        const defaultUsers = [
          { id: '1', username: '张三', email: 'zhangsan@example.com' },
          { id: '2', username: '李四', email: 'lisi@example.com' },
          { id: '3', username: '王五', email: 'wangwu@example.com' }
        ];
        userOptions.value = defaultUsers;
        filterForm.userId = defaultUsers[0].id;
        console.log(`已加载默认用户数据并选择: ${defaultUsers[0].username}`);
        await handleUserChange();
      }
      
      // 确保设置hasData为true，以便显示数据组件
      hasData.value = true;
        // 强制启用替代数据模式用于调试和演示
      localStorage.setItem('useMockData', 'true');
      
      loading.value = true;
      hasData.value = true;
        try {
        // 获取设备状态数据
        const statusParams = {
          userId: filterForm.userId,
          deviceId: filterForm.deviceId,
          startDate: filterForm.dateRange[0]?.toISOString(),
          endDate: filterForm.dateRange[1]?.toISOString()
        };          // 创建默认的替代设备状态数据，确保所有字段都有默认值
        const defaultStatusData = {
          status: 'online',
          lastActive: new Date().toISOString(),
          battery: 85,
          batteryLife: '约12小时',
          sensorHealth: 92,
          usageTime: '42小时',
          usageFrequency: '每日',
          humidity: 45,
          temperature: 23.5,
          pm25: 15,
          pm10: 28,
          co2: 650,
          tvoc: 320
        };
          // 如果使用模拟数据则使用模拟数据处理
        let statusData = {};
        try {
          // 检查是否使用替代数据模式
          const useMockDataMode = localStorage.getItem('useMockData') === 'true';
          
          if (useMockDataMode) {
            statusData = {...defaultStatusData};
          } else {
            const statusResponse = await getDeviceStatusData(statusParams);
            if (statusResponse && statusResponse.data && Object.keys(statusResponse.data).length > 0) {
              statusData = statusResponse.data;
            } else {
              statusData = {...defaultStatusData};
            }
          }
        } catch (error) {
          console.error('获取设备状态数据失败，使用备用数据替代:', error);
          statusData = {...defaultStatusData};
        }
        
        // 确保所有必需的字段都有值
        statusData = {
          ...defaultStatusData,
          ...statusData
        };
        
        console.log('最终使用的设备状态数据:', statusData);
        
        // 更新设备指标卡片数据
        updateDeviceMetrics(statusData);
        
        // 获取设备使用情况统计
        let usageData = { data: { dates: [], duration: [], activeTimes: [] } };
        try {
          usageData = await getDeviceUsageStats(
            filterForm.deviceId, 
            [filterForm.dateRange[0]?.toISOString(), filterForm.dateRange[1]?.toISOString()], 
            timeGranularity.value
          );        } catch (error) {          console.error('获取设备使用情况统计失败，使用替代数据:', error);
          // 创建替代数据
          const dates = [];
          const duration = [];
          const activeTimes = [];
          const startDate = new Date(filterForm.dateRange[0]);
          const endDate = new Date(filterForm.dateRange[1]);
          for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
            dates.push(d.toISOString().split('T')[0]);
            duration.push(Math.floor(Math.random() * 8) + 1); // 1-8小时
            activeTimes.push(Math.floor(Math.random() * 10) + 1); // 1-10次
          }
          usageData.data = { dates, duration, activeTimes };
        }
        
        // 获取设备异常数据
        let anomalyData = { data: { dates: [], values: [], anomalies: [] } };
        try {
          anomalyData = await getDeviceAnomalies({
            deviceId: filterForm.deviceId,
            startDate: filterForm.dateRange[0]?.toISOString(),
            endDate: filterForm.dateRange[1]?.toISOString()
          });
        } catch (error) {          console.error('获取设备异常数据失败，使用替代数据:', error);
          // 创建替代数据
          const dates = [];
          const values = [];
          const anomalies = [];
          const startDate = new Date(filterForm.dateRange[0]);
          const endDate = new Date(filterForm.dateRange[1]);
          for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
            const dateStr = d.toISOString().split('T')[0];
            dates.push(dateStr);
            const value = Math.floor(Math.random() * 100) + 50;
            values.push(value);
            // 随机添加一些异常点
            if (Math.random() > 0.8) {
              anomalies.push([dateStr, value * (Math.random() > 0.5 ? 1.5 : 0.5)]);
            }
          }
          anomalyData.data = { dates, values, anomalies };
        }
        
        // 获取设备告警分布
        let alertDistData = { data: [] };
        try {
          alertDistData = await getDeviceAlertDistribution({
            deviceId: filterForm.deviceId,
            startDate: filterForm.dateRange[0]?.toISOString(),
            endDate: filterForm.dateRange[1]?.toISOString()
          });
        } catch (error) {          console.error('获取设备告警分布数据失败，使用替代数据:', error);
          // 创建替代数据
          alertDistData.data = [
            { name: '设备离线', value: Math.floor(Math.random() * 5) + 1 },
            { name: '低电量', value: Math.floor(Math.random() * 5) + 1 },
            { name: '传感器故障', value: Math.floor(Math.random() * 3) },
            { name: '硬件故障', value: Math.floor(Math.random() * 2) },
            { name: '其他', value: Math.floor(Math.random() * 3) }
          ];
        }
        
        // 更新设备告警数据
        deviceAlertData.value = alertDistData.data || [
          { name: '设备离线', value: 0 },
          { name: '低电量', value: 0 },
          { name: '传感器故障', value: 0 },
          { name: '硬件故障', value: 0 },
          { name: '其他', value: 0 }
        ];
        
        // 更新图表
        updateUsageChart(usageData.data);
        updateAnomalyChart(anomalyData.data);
        updateAlertChart();
        
        // 如果选择了特定设备，加载其维护记录
        if (filterForm.deviceId) {
          let maintenanceData = { data: [] };
          try {
            maintenanceData = await getDeviceMaintenanceRecords(filterForm.deviceId);
          } catch (error) {            console.error('获取设备维护记录失败，使用替代数据:', error);
            // 创建替代数据
            maintenanceData.data = [
              {
                time: '2025-05-15 10:30',
                type: 'primary',
                color: '#409EFF',
                size: 'large',
                content: '设备例行维护检查'
              },
              {
                time: '2025-04-20 14:45',
                type: 'success',
                color: '#67C23A',
                size: 'normal',
                content: '传感器校准完成'
              },
              {
                time: '2025-03-10 09:15',
                type: 'warning',
                color: '#E6A23C',
                size: 'normal',
                content: '电池更换'
              },
              {
                time: '2025-01-25 16:00',
                type: 'danger',
                color: '#F56C6C',
                size: 'large',
                content: '主板维修更换'
              }
            ];
          }
          maintenanceRecords.value = maintenanceData.data || [];
        }
        
        // 加载历史数据表格
        loadHistoryTable();
        
      } catch (error) {
        console.error('分析数据失败:', error);
        ElMessage.error('分析数据失败，请稍后重试');
        hasData.value = false;
      } finally {
        loading.value = false;
      }
    };

    const resetFilter = () => {
      filterForm.userId = '';
      filterForm.deviceId = '';
      filterForm.dateRange = [new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000), new Date()];
      deviceOptions.value = [];
      hasData.value = false;
    };

    const exportData = async () => {
      if (!filterForm.userId) {
        ElMessage.warning('请选择用户和设备');
        return;
      }
      
      try {
        const params = {
          format: 'excel',
          userId: filterForm.userId,
          deviceId: filterForm.deviceId,
          startDate: filterForm.dateRange[0]?.toISOString(),
          endDate: filterForm.dateRange[1]?.toISOString()
        };
        
        let response;
        try {
          response = await exportDeviceData(params);
        } catch (error) {
          console.error('导出数据API调用失败，生成模拟导出文件:', error);
          // 创建模拟数据
          const mockData = new Blob(['时间戳,PM2.5,PM10,温度,湿度,TVOC,CO2,甲醛,电量,工作模式\n' +
            '2025-05-29 08:00:00,15,30,24.5,45,200,450,0.01,85,自动\n' +
            '2025-05-29 09:00:00,18,35,25.2,42,220,460,0.02,82,自动\n' +
            '2025-05-28 10:00:00,20,40,26.1,40,240,480,0.03,80,自动\n' +
            '2025-05-28 11:00:00,17,33,25.8,41,230,470,0.02,78,自动\n' +
            '2025-05-28 12:00:00,16,31,25.6,43,210,450,0.01,76,节能'], 
            {type: 'text/csv'});
          response = { data: mockData };
        }
        
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `设备数据_${new Date().toLocaleDateString()}.xlsx`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        ElMessage.success('数据导出成功');
      } catch (error) {
        console.error('导出数据失败:', error);
        ElMessage.error('导出数据失败，请稍后重试');
      }
    };    // 导出选中设备的数据
    const exportSelectedDevicesData = async () => {
      if (!selectedDevices.value || selectedDevices.value.length === 0) {
        ElMessage.warning('请先选择设备');
        return;
      }

      try {
        const params = {
          format: 'excel',
          deviceIds: selectedDevices.value,
          startDate: filterForm.dateRange[0]?.toISOString(),
          endDate: filterForm.dateRange[1]?.toISOString()
        };
        
        let response;
        try {
          response = await exportDeviceData(params);
        } catch (error) {
          console.error('导出选中设备数据API调用失败，生成模拟导出文件:', error);
          // 创建模拟数据
          const mockData = new Blob(['设备ID,设备名称,时间戳,PM2.5,PM10,温度,湿度,TVOC,CO2,甲醛,电量,工作模式\n'], 
            {type: 'text/csv'});
            
          // 为每个选中设备添加数据
          selectedDevices.value.forEach(deviceId => {
            const device = deviceList.value.find(d => d.id === deviceId) || { deviceName: `设备 ${deviceId}` };
            
            // 为每个设备添加5行随机数据
            for (let i = 0; i < 5; i++) {
              const date = new Date();
              date.setHours(date.getHours() - i);
              
              const dataLine = `${deviceId},${device.deviceName},` + 
                `${date.toLocaleString('zh-CN')},` +
                `${Math.floor(Math.random() * 50) + 10},` +
                `${Math.floor(Math.random() * 100) + 20},` +
                `${(Math.random() * 10 + 20).toFixed(1)},` +
                `${Math.floor(Math.random() * 30) + 40},` +
                `${Math.floor(Math.random() * 500) + 200},` +
                `${Math.floor(Math.random() * 1000) + 400},` +
                `${(Math.random() * 0.1).toFixed(3)},` +
                `${Math.floor(Math.random() * 100)},` +
                `${['自动', '手动', '睡眠', '节能'][Math.floor(Math.random() * 4)]}\n`;
                
              mockData.append(dataLine);
            }
          });
          
          response = { data: mockData };
        }
        
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `选中设备数据_${new Date().toLocaleDateString()}.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        ElMessage.success('选中设备数据导出成功');
      } catch (error) {
        console.error('导出选中设备数据失败:', error);
        ElMessage.error('导出数据失败，请稍后重试');
      }
    };
    
    // 数据大屏相关方法
    
    // 初始化数据大屏
    const initDashboard = () => {
      // 设置当前时间
      updateDashboardTime();
      
      // 刷新数据大屏
      refreshDashboard();
      
      // 每秒更新时间
      dashboardTimer.value = setInterval(() => {
        updateDashboardTime();
      }, 1000);
      
      // 每30秒刷新一次数据
      setInterval(() => {
        refreshDashboard();
      }, 30000);
    };
    
    // 刷新数据大屏
    const refreshDashboard = () => {
      // 根据选择的设备分组筛选设备数据
      let filteredDevices = [...deviceList.value];
      
      if (dashboardDeviceGroup.value !== 'all') {
        // 找到当前选择的分组
        let currentGroup;
        // 先从系统分组中查找
        currentGroup = deviceGroups.value.find(g => g.id === dashboardDeviceGroup.value);
        
        // 如果在系统分组中没找到，则从自定义分组查找
        if (!currentGroup) {
          currentGroup = customGroups.value.find(g => g.id === dashboardDeviceGroup.value);
        }
        
        if (currentGroup) {
          // 根据分组筛选设备
          filteredDevices = deviceList.value.filter(device => 
            currentGroup.deviceIds.includes(device.id)
          );
        }
      }
      
      // 根据排序方式对设备进行排序
      switch (dashboardSortBy.value) {
        case 'status':
          // 按状态排序 (正常 > 警告 > 离线)
          filteredDevices.sort((a, b) => {
            const statusPriority = { '正常': 0, '电量低': 1, '警告': 1, '告警': 1, '离线': 2 };
            return statusPriority[a.status] - statusPriority[b.status];
          });
          break;
          
        case 'battery':
          // 按电量排序 (从高到低)
          filteredDevices.sort((a, b) => b.batteryLevel - a.batteryLevel);
          break;
          
        case 'active':
          // 按最后活跃时间排序 (从新到旧)
          filteredDevices.sort((a, b) => {
            return new Date(b.lastActive) - new Date(a.lastActive);
          });
          break;
      }
      
      // 更新数据大屏设备列表
      dashboardDeviceList.value = filteredDevices.slice(0, 10); // 只显示前10个设备
      
      // 更新图表
      updateDashboardCharts();
    };
    
    // 更新数据大屏时间
    const updateDashboardTime = () => {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      
      currentTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };
    
    // 更新数据大屏图表
    const updateDashboardCharts = () => {
      nextTick(() => {
        // 健康状态饼图
        const healthChartDom = document.getElementById('dashboardHealthChart');
        if (healthChartDom) {
          const healthChart = echarts.init(healthChartDom);          const healthOption = {
            color: ['#67C23A', '#E6A23C', '#F56C6C'],
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)',
              textStyle: {
                fontFamily: 'Microsoft YaHei, Arial, sans-serif'
              }
            },
            legend: {
              orient: 'vertical',
              right: 10,
              top: 'center',
              textStyle: {
                color: '#fff',
                fontFamily: 'Microsoft YaHei, Arial, sans-serif'
              }
            },
            series: [
              {
                name: '健康状态',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                },
                data: [
                  { value: deviceMetrics.value.healthStatus.normal, name: '正常' },
                  { value: deviceMetrics.value.healthStatus.warning, name: '警告' },
                  { value: deviceMetrics.value.healthStatus.error, name: '故障' }
                ]
              }
            ]
          };
          healthChart.setOption(healthOption);
        }
        
        // 异常检测图表
        const anomalyChartDom = document.getElementById('dashboardAnomalyChart');
        if (anomalyChartDom) {
          const anomalyChart = echarts.init(anomalyChartDom);
          
          // 生成最近7天的日期
          const dates = [];
          const pm25Data = [];
          const pm10Data = [];
          
          for (let i = 6; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            dates.push(date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' }));
            pm25Data.push(Math.floor(Math.random() * 50) + 10);
            pm10Data.push(Math.floor(Math.random() * 100) + 20);
          }
            const anomalyOption = {
            color: ['#409EFF', '#91CC75'],
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            tooltip: {
              trigger: 'axis',
              textStyle: {
                fontFamily: 'Microsoft YaHei, Arial, sans-serif'
              }
            },
            legend: {
              data: ['PM2.5', 'PM10'],
              textStyle: {
                color: '#fff',
                fontFamily: 'Microsoft YaHei, Arial, sans-serif'
              }
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: dates,
              axisLine: {
                lineStyle: {
                  color: '#fff'
                }
              }
            },
            yAxis: {
              type: 'value',
              axisLine: {
                lineStyle: {
                  color: '#fff'
                }
              },
              splitLine: {

                lineStyle: {
                  color: 'rgba(255,255,255,0.1)'
                }
              }
            },
            series: [
              {
                name: 'PM2.5',
                type: 'line',
                data: pm25Data,
                markPoint: {
                  data: [
                    { type: 'max', name: '最大值' },
                    { type: 'min', name: '最小值' }
                  ]
                }
              },
              {
                name: 'PM10',
                type: 'line',
                data: pm10Data
              }
            ]
          };
          anomalyChart.setOption(anomalyOption);
        }
        
        // 告警分布图表
        const alertChartDom = document.getElementById('dashboardAlertChart');
        if (alertChartDom) {
          const alertChart = echarts.init(alertChartDom);
          const alertOption = {
            color: ['#F56C6C', '#E6A23C', '#409EFF', '#67C23A', '#909399'],
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              right: 10,
              top: 'center'
            },
            series: [
              {
                name: '告警类型',
                type: 'pie',
                radius: '50%',
                data: [
                  { value: Math.floor(Math.random() * 5) + 1, name: 'PM2.5超标' },
                  { value: Math.floor(Math.random() * 8) + 2, name: '电量不足' },
                  { value: Math.floor(Math.random() * 3) + 1, name: '设备离线' },
                  { value: Math.floor(Math.random() * 4) + 1, name: 'CO浓度异常' },
                  { value: Math.floor(Math.random() * 3), name: '传感器故障' }
                ],
                emphasis: {
                 
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]          };
          alertChart.setOption(alertOption);
        }
      });
    };
    
    // 更新使用情况图表
    const updateUsageChart = (data = null) => { // eslint-disable-line no-unused-vars
      nextTick(() => {
        // 通过DOM元素获取图表容器
        const chartDom = document.querySelector('.device-analysis-container #usageChart') || usageChart.value;
        if (!chartDom) {
          console.error('找不到使用情况图表容器');
          return;
        }
        
        // 确保echarts实例存在
        let chart = echarts.getInstanceByDom(chartDom);
        if (!chart) {
          console.log('初始化使用情况图表实例');
          chart = echarts.init(chartDom);
        }
        
        // 准备图表数据
        let categories = [];
        let values = [];
        
        // 如果传入了数据，使用传入的数据
        if (data && data.dates && data.dates.length > 0) {
          console.log('使用传入的使用情况数据', data);
          categories = data.dates;
          
          // 根据选择的指标显示不同的数据
          if (usageChartMetric.value === 'duration') {
            values = data.duration || [];
          } else if (usageChartMetric.value === 'activeTimes') {
            values = data.activeTimes || [];
          } else if (usageChartMetric.value === 'batteryUsage') {
            values = data.batteryUsage || [];
          }        } else {
          // 使用模拟数据
          console.log('[API调用] GET /device/usageStats - 向后端获取设备使用情况数据');
          // 生成近7天的日期
          for (let i = 6; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            categories.push(date.toLocaleDateString('zh-CN'));
            // 根据不同的指标生成不同范围的模拟数据
            if (usageChartMetric.value === 'duration') {
              values.push(Math.floor(Math.random() * 8) + 2); // 2-10小时
            } else if (usageChartMetric.value === 'activeTimes') {
              values.push(Math.floor(Math.random() * 15) + 5); // 5-20次
            } else if (usageChartMetric.value === 'batteryUsage') {
              values.push(Math.floor(Math.random() * 30) + 10); // 10-40%
            } else {
              values.push(Math.floor(Math.random() * 100) + 20);
            }
          }
        }
        
        // 根据选择的指标设置不同的标题和Y轴名称
        let metricTitle = '设备使用时长';
        let yAxisName = '使用时长(小时)';
        let color = '#409EFF';
        
        if (usageChartMetric.value === 'activeTimes') {
          metricTitle = '设备使用次数';
          yAxisName = '使用次数(次)';
          color = '#67C23A';
        } else if (usageChartMetric.value === 'batteryUsage') {
          metricTitle = '设备电量消耗';
          yAxisName = '电量消耗(%)';
          color = '#E6A23C';
        }
        
        const option = {
          title: {
            text: metricTitle,
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: categories
          },
          yAxis: {
            type: 'value',
            name: yAxisName
          },
          series: [{
            type: 'bar',
            data: values,
            itemStyle: {
              color: color
            }
          }]
        };
          chart.setOption(option);
      });
    };
    
    // 更新异常检测图表
    const updateAnomalyChart = (data = null) => { // eslint-disable-line no-unused-vars
      nextTick(() => {
        // 通过DOM元素获取图表容器
        const chartDom = document.querySelector('.device-analysis-container #anomalyChart') || anomalyChart.value;
        if (!chartDom) {
          console.error('找不到异常检测图表容器');
          return;
        }
        
        // 确保echarts实例存在
        let chart = echarts.getInstanceByDom(chartDom);
        if (!chart) {
          console.log('初始化异常检测图表实例');
          chart = echarts.init(chartDom);
        }
          // 准备时间序列数据
        let dates = [];
        let values = [];
        let anomalies = [];
        
        // 如果传入了数据，使用传入的数据
        if (data && data.dates && data.dates.length > 0) {
          console.log('使用传入的异常检测数据', data);
          dates = data.dates;
          values = data.values || [];
          
          // 如果有异常点数据，处理异常点
          if (data.anomalies && data.anomalies.length > 0) {
            // 转换异常点格式为echarts需要的格式
            anomalies = data.anomalies.map((anomaly) => { // eslint-disable-line no-unused-vars
              const dateIndex = dates.indexOf(anomaly[0]);
              return dateIndex >= 0 ? [dateIndex, anomaly[1]] : null;
            }).filter(item => item !== null);
          }
        } else {          // 使用模拟数据
          console.log('[API调用] GET /device/anomalies - 向后端获取设备异常检测数据');
          // 生成近7天的日期和数据
          for (let i = 0; i < 7; i++) {
            const date = new Date();
            date.setDate(date.getDate() - (6-i));
            const dateStr = date.toLocaleDateString('zh-CN');
            dates.push(dateStr);
            
            // 根据不同指标生成合适范围的模拟数据
            let value = 0;
            switch(anomalyMetric.value) {
              case 'pm25':
                value = Math.floor(Math.random() * 30) + 10; // 10-40 μg/m³
                break;
              case 'pm10':
                value = Math.floor(Math.random() * 50) + 20; // 20-70 μg/m³
                break;
              case 'co2':
                value = Math.floor(Math.random() * 300) + 400; // 400-700 ppm
                break;
              case 'tvoc':
                value = Math.floor(Math.random() * 200) + 100; // 100-300 ppb
                break;
              case 'temperature':
                value = Math.floor(Math.random() * 10) + 18; // 18-28 °C
                break;
              default:
                value = Math.floor(Math.random() * 50) + 25;
            }
            
            values.push(value);
            
            // 随机生成异常点 (20-30% 的数据点是异常的)
            if (Math.random() > 0.7) {
              // 异常值可能是正常值的1.5倍高或0.5倍低
              anomalies.push([i, value * (Math.random() > 0.5 ? 1.5 : 0.5)]);
            }
          }
        }
        
        // 根据选择的指标设置不同的标题和Y轴名称
        let metricTitle = '设备异常检测';
        let yAxisName = '';
        
        switch(anomalyMetric.value) {
          case 'pm25':
            metricTitle = 'PM2.5异常检测';
            yAxisName = 'PM2.5 浓度(μg/m³)';
            break;
          case 'pm10':
            metricTitle = 'PM10异常检测';
            yAxisName = 'PM10 浓度(μg/m³)';
            break;
          case 'co2':
            metricTitle = 'CO2异常检测';
            yAxisName = 'CO2 浓度(ppm)';
            break;
          case 'tvoc':
            metricTitle = 'TVOC异常检测';
            yAxisName = 'TVOC 浓度(μg/m³)';
            break;
          case 'temperature':
            metricTitle = '温度异常检测';
            yAxisName = '温度(℃)';
            break;
        }
        
        const option = {
          title: {
            text: metricTitle,
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: dates
          },
          yAxis: {
            type: 'value',
            name: yAxisName
          },
          series: [{
            type: 'line',
            data: values,
            itemStyle: {
              color: '#409EFF'
            },
            markPoint: showAnomalies.value && anomalies.length > 0 ? {
              data: anomalies.map(([x, y]) => ({
                coord: [x, y],
                symbol: 'circle',
                symbolSize: 10,
                itemStyle: {
                  color: '#F56C6C'
                },
                label: {
                  formatter: '异常',
                  position: 'top'
                }
              }))
            } : undefined
          }]
        };
        
        chart.setOption(option);
      });
    };
      // 更新告警分布图表
    const updateAlertChart = () => {
      nextTick(() => {
        // 通过DOM元素获取图表容器
        const chartDom = document.querySelector('.device-analysis-container #alertChart') || alertChart.value;
        if (!chartDom) {
          console.error('找不到告警分布图表容器');
          return;
        }
        
        // 确保echarts实例存在
        let chart = echarts.getInstanceByDom(chartDom);
        if (!chart) {
          console.log('初始化告警分布图表实例');
          chart = echarts.init(chartDom);
        }
        
        let alertData = [];
        
        // 如果有设备告警数据，使用现有数据
        if (deviceAlertData.value && deviceAlertData.value.length > 0) {
          // 根据分组方式处理数据
          if (alertGroupBy.value === 'device') {
            // 获取设备列表中的名称
            alertData = deviceList.value.slice(0, 5).map(device => ({
              name: device.deviceName || `设备${device.id}`,
              value: Math.floor(Math.random() * 10) + 1
            }));
          } else if (alertGroupBy.value === 'severity') {
            // 按严重程度分组
            alertData = [
              { name: '严重', value: Math.floor(Math.random() * 5) + 1 },
              { name: '警告', value: Math.floor(Math.random() * 8) + 3 },
              { name: '一般', value: Math.floor(Math.random() * 15) + 5 }
            ];
          } else {
            // 默认按类型分组
            alertData = deviceAlertData.value;
          }
        } else {
          // 没有数据，使用默认数据
          const alertTypes = ['设备离线', '低电量', '传感器故障', '硬件故障', '其他'];
          alertData = alertTypes.map(type => ({
            name: type,
            value: Math.floor(Math.random() * 10) + 1
          }));
        }
          const option = {
          title: {
            text: '告警分布',
            left: 'center',
            textStyle: {
              fontFamily: 'Microsoft YaHei, Arial, sans-serif'
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)',
            textStyle: {
              fontFamily: 'Microsoft YaHei, Arial, sans-serif'
            }
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            textStyle: {
              fontFamily: 'Microsoft YaHei, Arial, sans-serif'
            }
          },
          series: [{
            name: '告警类型',
            type: alertViewType.value === 'pie' ? 'pie' : 'bar',
            data: alertData,
            radius: alertViewType.value === 'pie' ? '70%' : undefined,
            label: {
              show: true,
              formatter: '{b}',
              fontFamily: 'Microsoft YaHei, Arial, sans-serif'
            }
          }]
        };
        
        chart.setOption(option);
      });
    };
    
    // 处理表格分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size;
      currentPage.value = 1;
      loadHistoryTable();
    };
    
    // 处理表格当前页变化
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      loadHistoryTable();
    };
      // 加载历史数据表格
    const loadHistoryTable = () => {
      tableLoading.value = true;
      
      // 模拟表格数据
      const mockData = [];
      for (let i = 0; i < pageSize.value; i++) {
        // 生成当前日期前的某个随机时间
        const recordDate = new Date();
        recordDate.setDate(recordDate.getDate() - Math.floor(Math.random() * 7)); // 最近7天内的随机日期
        recordDate.setHours(Math.floor(Math.random() * 24)); // 随机小时
        recordDate.setMinutes(Math.floor(Math.random() * 60)); // 随机分钟
        
        // 基础的环境数据数值
        const pm25Value = Math.floor(Math.random() * 100) + 10;
        const pm10Value = Math.floor(Math.random() * 150) + 20;
        const tempValue = (Math.random() * 15 + 18).toFixed(1); // 18-33°C
        const humidityValue = Math.floor(Math.random() * 60) + 30; // 30-90%
        const tvocValue = Math.floor(Math.random() * 500) + 50; // 50-550 ppb
        const co2Value = Math.floor(Math.random() * 800) + 400; // 400-1200 ppm
        const hchoValue = (Math.random() * 0.08 + 0.02).toFixed(2); // 0.02-0.10 mg/m³
        
        // 设备电池电量
        const batteryLevel = Math.floor(Math.random() * 100) + 1; // 1-100%
        
        // 工作模式
        const workModes = ['自动', '睡眠', '强力', '节能', '自定义'];
        const workMode = workModes[Math.floor(Math.random() * workModes.length)];
          // 如果指定了设备，使用该设备名称，否则使用标准格式设备名
        let deviceName = '';
        if (dataRecordDevice.value && deviceList.value) {
          const device = deviceList.value.find(d => d.id === dataRecordDevice.value);
          deviceName = device ? device.deviceName : generateDeviceName(100 + (i % 26), (i % 99) + 1);
        } else {
          deviceName = generateDeviceName(100 + (i % 26), (i % 99) + 1);
        }
        
        mockData.push({
          id: i + 1 + (currentPage.value - 1) * pageSize.value,
          deviceName: deviceName,
          timestamp: recordDate.toLocaleString(),
          pm25: pm25Value,
          pm10: pm10Value,
          temperature: tempValue,
          humidity: humidityValue,
          tvoc: tvocValue,
          co2: co2Value,
          hcho: hchoValue,
          batteryLevel: batteryLevel,
          workMode: workMode
        });
      }
      
      setTimeout(() => {
        tableData.value = mockData;
        total.value = 100; // 模拟总数
        tableLoading.value = false;
      }, 1000);
    };
    
    // 导出表格数据
    const exportTableData = () => {
      if (tableData.value.length === 0) {
        ElMessage.warning('没有可导出的数据');
        return;
      }
      
      try {
        // 创建CSV格式数据
        const headers = ['设备名称', '时间戳', 'PM2.5', 'PM10', '温度', '湿度', '状态'];
        const csvContent = [
          headers.join(','),
          ...tableData.value.map(row => [
            row.deviceName,
            row.timestamp,
            row.pm25,
            row.pm10,
            row.temperature,
            row.humidity,
            row.status
          ].join(','))
        ].join('\n');
        
        // 创建下载链接
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `设备数据_${new Date().toLocaleDateString()}.csv`;
        link.click();
        
        ElMessage.success('数据导出成功');
      } catch (error) {
        console.error('导出数据失败:', error);
        ElMessage.error('导出数据失败');
      }
    };
    
    // 处理设备分组变化
    const handleDeviceGroupChange = (groupId) => {
      currentDeviceGroup.value = groupId;
      updateFilteredDevices();
    };
    
    // 处理设备搜索
    const handleDeviceSearch = (query) => {
      deviceSearchQuery.value = query;
      updateFilteredDevices();
    };
    
    // 更新过滤后的设备列表
    const updateFilteredDevices = () => {
      // 根据当前分组和搜索条件过滤设备
      console.log('更新过滤设备列表:', currentDeviceGroup.value, deviceSearchQuery.value);
    };
    
    // 处理更多操作
    const handleMoreActions = (action) => {
      switch (action) {
        case 'export':
          exportSelectedDevicesData();
          break;
        case 'group':
          showGroupDialog.value = true;
          groupDialogTab.value = 'create';
          break;
        default:
          console.log('未知操作:', action);
      }
    };
    
    // 保存设备分组
    const saveDeviceGroup = async () => {
      try {
        if (isEditingGroup.value) {
          // 更新现有分组
          const groupIndex = customGroups.value.findIndex(g => g.id === currentEditingGroupId.value);
          if (groupIndex !== -1) {
            customGroups.value[groupIndex] = {
              ...customGroups.value[groupIndex],
              name: newGroupForm.name,
              deviceIds: [...newGroupForm.deviceIds]
            };
          }
          ElMessage.success('分组更新成功');
        } else {
          // 创建新分组
          const newGroup = {
            id: `custom_${Date.now()}`,
            name: newGroupForm.name,
            deviceIds: [...newGroupForm.deviceIds]
          };
          customGroups.value.push(newGroup);
          deviceGroups.value.push(newGroup);
          ElMessage.success('分组创建成功');
        }
        
        showGroupDialog.value = false;
        resetGroupForm();
      } catch (error) {
        console.error('保存分组失败:', error);
        ElMessage.error('保存分组失败');
      }
    };
    
    // 重置分组表单
    const resetGroupForm = () => {
      newGroupForm.name = '';
      newGroupForm.deviceIds = [];
      isEditingGroup.value = false;
      currentEditingGroupId.value = '';
    };
    
    // 编辑分组
    const editGroup = (group) => {
      isEditingGroup.value = true;
      currentEditingGroupId.value = group.id;
      newGroupForm.name = group.name;
      newGroupForm.deviceIds = [...group.deviceIds];
      showGroupDialog.value = true;
      groupDialogTab.value = 'create';
    };
    
    // 删除分组
    const deleteGroup = async (group) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除分组"${group.name}"吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        // 从自定义分组中删除
        const customIndex = customGroups.value.findIndex(g => g.id === group.id);
        if (customIndex !== -1) {
          customGroups.value.splice(customIndex, 1);
        }
        
        // 从设备分组中删除
        const groupIndex = deviceGroups.value.findIndex(g => g.id === group.id);
        if (groupIndex !== -1) {
          deviceGroups.value.splice(groupIndex, 1);
        }
        
        // 如果当前选择的是被删除的分组，切换到全部设备
        if (currentDeviceGroup.value === group.id) {
          currentDeviceGroup.value = 'all';
        }
        
        ElMessage.success('分组删除成功');
      } catch (error) {
        // 用户取消删除
        if (error === 'cancel') {
          return;
        }
        console.error('删除分组失败:', error);
        ElMessage.error('删除分组失败');
      }
    };
    
    // 获取设备头像颜色
    const getDeviceAvatarColor = (device) => {
      if (device.status === '正常') return '#67C23A';
      if (device.status === '警告' || device.status === '电量低') return '#E6A23C';
      if (device.status === '告警') return '#F56C6C';
      return '#909399';    };
    
    // 获取电池颜色
    const getBatteryColor = (percentage) => {
      if (percentage < 20) return '#F56C6C';
      if (percentage < 50) return '#E6A23C';
      return '#67C23A';
    };

    // 组件挂载时初始化用户数据
    onMounted(async () => {
      console.log('DataAnalysis组件已挂载，开始初始化用户数据...');
      loading.value = true;
      
      try {
        // 获取用户列表
        const response = await getUsersList();
        
        if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
          userOptions.value = response.data;
          console.log('成功加载用户列表:', userOptions.value.length, '个用户');
        } else {
          console.warn('API返回的用户列表为空，使用默认用户数据');
          // 使用默认用户数据
          userOptions.value = [
            { id: '1', username: '张三', email: 'zhangsan@example.com' },
            { id: '2', username: '李四', email: 'lisi@example.com' },
            { id: '3', username: '王五', email: 'wangwu@example.com' }
          ];
        }
        
        // 自动选择第一个用户并加载数据
        if (userOptions.value.length > 0) {
          filterForm.userId = userOptions.value[0].id;
          console.log('自动选择第一个用户:', filterForm.userId);
            // 加载该用户的设备
          const devices = await handleUserChange();
          
          // 如果有设备，自动选择第一个设备
          if (devices && devices.length > 0) {
            filterForm.deviceId = devices[0].id;
            console.log('自动选择第一个设备:', filterForm.deviceId);
          }
          
          // 强制设置hasData为true，确保显示数据          console.log('设置hasData为true');
          hasData.value = true;
          
          // 确保设备数据被加载
          await fetchDevicesList();
          
          // 自动分析数据
          await analyzeData();
          console.log('自动加载数据分析完成');
        }
      } catch (error) {
        console.error('获取用户列表失败，使用默认用户数据:', error);
        
        // 发生错误时使用默认用户数据
        userOptions.value = [
          { id: '1', username: '张三', email: 'zhangsan@example.com' },
          { id: '2', username: '李四', email: 'lisi@example.com' },
          { id: '3', username: '王五', email: 'wangwu@example.com' }
        ];
        
        // 显示用户友好的错误消息
        ElMessage.warning('用户数据加载失败，已使用默认数据');
        
        // 尽管发生错误，仍然尝试加载默认数据
        filterForm.userId = userOptions.value[0].id;
        await handleUserChange();        hasData.value = true; // 确保显示数据
        await fetchDevicesList(); // 确保设备数据被加载
        await analyzeData();
      } finally {
        loading.value = false;
      }
    });

    // 导出方法和响应式状态
    return {
      loading,
      tableLoading,
      hasData,
      isMobile,
      deviceList,
      selectedDevices,
      deviceTableData,
      totalDeviceCount,
      deviceCurrentPage,
      devicePageSize,
      dataRecordDevice,
      maintenanceDevice,
      maintenanceTab,
      usageChartMetric,
      anomalyMetric,
      alertViewType,
      alertGroupBy,
      deviceMetrics,
      isDev,
      filterForm,
      userOptions,
      deviceOptions,
      dateShortcuts,
      timeGranularity,
      showAnomalies,
      tableData,
      total,
      pageSize,
      currentPage,
      usageChart,
      anomalyChart,
      alertChart,
      deviceStatus,
      deviceLastActive,
      deviceBattery,
      deviceBatteryStatus,
      batteryLifeRemaining,
      sensorHealth,
      sensorHealthStatus,
      sensorHealthMessage,
      deviceUsageTime,
      usageFrequency,
      maintenanceRecords,
      handleUserChange,
      analyzeData,
      resetFilter,
      updateUsageChart,
      updateAnomalyChart,
      updateAlertChart,
      handleSizeChange,
      handleCurrentChange,
      handleDevicePageChange,
      handleDeviceSelection,      fetchHistoricalData,
      updateMaintenanceRecords,
      handleMaintenanceTabChange,
      exportData,
      exportTableData,
      getStatusType,
      getBatteryStatus,
      fetchDevicesList,
      refreshDevicesList,
      
      // 新增设备分组相关
      deviceGroups,
      currentDeviceGroup,
      customGroups,
      isAddingGroup,
      newGroupForm,
      showGroupDialog,
      groupDialogTab,
      isEditingGroup,
      currentEditingGroupId,
      deviceSearchQuery,
      groupFormRules,
      handleDeviceGroupChange,
      handleDeviceSearch,
      handleMoreActions,
      saveDeviceGroup,
      resetGroupForm,
      editGroup,
      deleteGroup,
        // 数据大屏相关
      showDashboardDialog,
      currentTime,
      dashboardTimer,
      dashboardDeviceGroup,
      dashboardSortBy,
      dashboardDeviceList,
      initDashboard,
      refreshDashboard,
      updateDashboardTime,
      updateDashboardCharts,
      getDeviceAvatarColor,
      getBatteryColor,
      exportSelectedDevicesData
    };
  }
};
</script>

<style scoped>
.data-analysis-container {
  padding: 10px;
}

.analysis-card {
  min-height: 600px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-row {
  margin-bottom: 20px;
}

.metrics-row {
  margin-bottom: 20px;
}

.metric-card {
  height: 100px;
  text-align: center;
  margin-bottom: 15px;
}

.metric-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.metric-value.good {
  color: #67c23a;
}

.metric-value.normal {
  color: #409EFF;
}

.metric-value.warning {
  color: #e6a23c;
}

.metric-value.danger {
  color: #f56c6c;
}

.metric-compare {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.chart-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trend-chart {
  height: 400px;
  width: 100%;
}

.distribution-row {
  margin-bottom: 20px;
}

.distribution-chart,
.heatmap-chart {
  height: 350px;
  width: 100%;
}

.data-table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.value-warning {
  color: #f56c6c;
}

.value-normal {
  color: #67c23a;
}

/* 响应式布局样式 */
@media (max-width: 768px) {
  .filter-row {
    padding: 10px 0;
  }
  
  .responsive-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .button-item {
    display: flex;
    justify-content: space-between;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .chart-actions {
    margin-top: 5px;
    width: 100%;
  }
  
  .chart-actions .el-radio-group {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
  
  .el-pagination {
    justify-content: center !important;
  }
  
  /* 强制表格适配小屏幕 */
  .el-table {
    width: 100%;
    overflow-x: auto;
  }
  
  /* 表格分页适配 */
  .pagination {
    padding-top: 10px;
    overflow-x: auto;
    white-space: nowrap;
    text-align: center !important;
  }
}

/* 设备分组相关样式 */
.empty-custom-groups {
  padding: 40px 0;
  text-align: center;
}

/* 数据大屏相关样式 */
.dashboard-dialog .el-dialog__body {
  padding: 0;
  background-color: #0a1929;
  color: #fff;
}

.dashboard-container {
  height: 100vh;
  padding: 20px;
  overflow-y: auto;
  background-color: #0a1929;
  color: #fff;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.dashboard-header h2 {
  margin: 0;
  color: #fff;
  font-size: 24px;
}

.dashboard-time {
  font-size: 18px;
  color: #67C23A;
  font-weight: bold;
}

.dashboard-card {
  background-color: #0c223a;
  border-radius: 8px;
  padding: 20px;
  height: 100%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.dashboard-title {
  font-size: 16px;
  margin-bottom: 15px;
  color: #89a8d0;
  font-weight: bold;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding-bottom: 10px;
}

.dashboard-info {
  display: flex;
  flex-direction: column;
  height: calc(100% - 45px);
  justify-content: space-around;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.info-label {
  font-size: 14px;
  color: #89a8d0;
}

.info-value {
  font-size: 22px;
  font-weight: bold;
  color: #fff;
}

.dashboard-battery {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100% - 45px);
}

.dashboard-device-list {
  height: calc(100% - 45px);
  overflow-y: auto;
}

/* 自定义表格样式 */
.dashboard-device-list .el-table {
  background-color: transparent !important;
  color: #fff;
}

.dashboard-device-list .el-table tr {
  background-color: transparent !important;
}

.dashboard-device-list .el-table td {
  border-bottom-color: rgba(255, 255, 255, 0.1);
}

.device-info {
  display: flex;
  flex-direction: column;
}

.device-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.device-status {
  display: flex;
  align-items: center;
}
</style>
